<html>
<head>
	<style type="text/css">
		body {
			
			margin: 0 0 0 0;
			padding: 0px;
			color: #093E41;
			font-family: Tahoma;
		}
		a {
			display: block;
			padding: 4px;
			text-decoration:none;
			font-size: 12px;
			padding:4px;
			color:#004080;
		}
		a:hover{
			color: #f00;
			
		}
		div {
			min-width: 170px;
		}
		
		.bookmarkList-container{
			
			color:#F00;
			font-size:10px;
		}
		
		.totalBookmarks-container {
			font-size:10px;			
		}
		
		.bookmarkURL{
			font-size:9px;
			color:#d6d6d6;
		}
		
		.labelHeader {
			font-size:14px;
			color:#6F6F6F;
			text-decoration : none; 
			background-color:#EFEFEF;
		}
		
		.labelHeader:hover{
			color:#FFFFFF;
			background-color:#6F6F6F;
		}
		
		.displayNone {
			display:none;
		}
	</style>
		
    <script>


        // *************************************************************************
        // the google bookmarks as an XML file
        var bookmarksXML = "http://www.google.com/bookmarks/?output=xml&num=100000";

        // Google bookmarks page needed to log in etc.....
        var googlebookmarks = "http://www.google.com/bookmarks/";

        // *************************************************************************

        var unreadCount;

        var xmlDoc;
        var xmlLabelDoc;

        var labels;
        var bookmarks;

        /**
         * Return the total number of google bookmarks
         */
        function getTotalNumGoogleBookmarks() {
            // display the total number of bookmarks
            chrome.browserAction.setBadgeText({text:""+xmlDoc.getElementsByTagName("bookmark").length+""});
			document.getElementById('bookmarkListcontainer').innerHTML = "<div class='totalBookmarks-container' id='totalBookmarks-container'><strong>Total Bookmarks:</strong> " + xmlDoc.getElementsByTagName("bookmark").length + "</div><br>";
	
        }

        /**
         * Display Google management links
         */
        function getGoogleManagmentLinks() {

            chrome.tabs.getSelected(null, function(tab) {
                var url = tab.url;
                var title = tab.title;

                var addGoogleBookmarkURL = "http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=\"" + url + "\"&title=\"" + title + "\"";
				
				document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML + "<div>";
                document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML + "<a href='" + addGoogleBookmarkURL + "' target='_blank'><img src='book_add.png' align='top'> Bookmark this page...</a><";

                document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML +  "<a href='" + googlebookmarks + "' target='_blank'>Manage all...</a>";
                document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML +  "</div>";

            });
        }

        /**
         * get the bookmarks
         */
        function getBookmarks() {

            // read through one bookmark tag at a time.
            var bookmark = xmlDoc.getElementsByTagName("bookmark");
			
			
            for (var i = 0; i < bookmark.length; i++) {
                var titles = bookmark[i].getElementsByTagName("title");
                var url = bookmark[i].getElementsByTagName("url");

                var urlNodeValue = url[0].firstChild.nodeValue;
                var titleNodeValue = titles[0].firstChild.nodeValue;

                document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML + "<a href='" + urlNodeValue + "' target='_blank' title='" + titleNodeValue + "'>" + titleNodeValue + "</a>";
            }
        }

        /**
         * display a search text input for the user to type into
         */
        function displaySearch() {
            document.write("<P><LABEL ACCESSKEY=S>Search Bookmarks: <INPUT TYPE=text NAME=username SIZE=20></LABEL></P>");
        }


        /**
         * load all the labels from google bookmarks.
         */
        function getLabels() {

            var labelsArray = new Array();

            // get all the labels from the XML - NOTE: these maybe duplicated
            var labels = xmlDoc.getElementsByTagName("label");
            for (var i = 0; i < labels.length; i++) {
                var labelNodeValue = labels[i].firstChild.nodeValue;
                labelsArray[i] = labelNodeValue;
            }

            // display the labels
            var displayLabels = unique(labelsArray).sort();
			
			// add label on the end of array to get unlabelled items
			displayLabels.push("^none");
            labelContent = '';
        				
            for (var j = 0; j < displayLabels.length; j++) {
    
            	labelName = displayLabels[j];
            	labelNumber = j;

            	
                labelContent = labelContent +  "<a href=\"#\" onClick=\"toggleLayer('label"+labelNumber+"');getBookmarkForLabel('"+labelName+"','"+labelNumber+"');return false;\" class=\"labelHeader\">" + labelName + " ()</a>";
                labelContent = labelContent +  "<div id=\"label"+labelNumber+"\" style=\"display:none;width:350px;\">";
                labelContent = labelContent +  "</div>";
	

                //getBookmarkForLabel(displayLabels[j],j);
            }

            document.getElementById('bookmarkListcontainer').innerHTML = document.getElementById('bookmarkListcontainer').innerHTML + labelContent;
			
        }

        /**
         * Return the count of the bookmarks for the given label
         * i.e Utilities (10)
         *
         * @param labelName
         */
        function getBookmarkForLabel(labelName,labelNumber) {

            // create a new request object
            var xhr1 = new XMLHttpRequest();

            try {

                // if we have an onReadyStateChange of 4 then we can read the XML
                xhr1.onreadystatechange = function() {
                    if (xhr1.readyState == 4) {
                        if (xhr1.responseXML) {

                            xmlLabelDoc = xhr1.responseXML;

                            // read through one bookmark tag at a time.
                            var bookmark = xmlLabelDoc.getElementsByTagName("bookmark");

                            labelContent = '';


                            // Display the bookmark information
                            for (var i = 0; i < bookmark.length; i++) {
								if (bookmark[i].getElementsByTagName("title")){
                                var titles = bookmark[i].getElementsByTagName("title");
                                var titleNodeValue = titles[0].firstChild.nodeValue;
								}else{
								var titleNodeValue = '';
								}

								if (bookmark[i].getElementsByTagName("url")){
                                var url = bookmark[i].getElementsByTagName("url");
                                var urlNodeValue = url[0].firstChild.nodeValue;
								}else{
								var urlNodeValue = '';
								}
                                
                                
                                
                                if (bookmark[i].getElementsByTagName("attribute")){
	                                var attributes = bookmark[i].getElementsByTagName("attribute");
	
	                                var n_titles = attributes.length;
	                                if (n_titles !=0){
	                                for (x = 0; x < n_titles; x++) {
									  //document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + attributes[x].childNodes[0].firstChild.nodeValue + " | "+ attributes[x].childNodes[1].firstChild.nodeValue +"<br>";
	
									  	if (attributes[x].childNodes[0].firstChild.nodeValue){
										  	if (attributes[x].childNodes[0].firstChild.nodeValue == 'favicon_url'){
												favi_icon_url=attributes[x].childNodes[1].firstChild.nodeValue;
									  		}else{
												favi_icon_url='http://www.google.com/favicon.ico';
									  		}
									  	}else{
											favi_icon_url='http://www.google.com/favicon.ico';
									  	}
									}
	                                }else{
	                                	favi_icon_url='http://www.google.com/favicon.ico';
	                                }
	
	                                if (favi_icon_url=='notfound'){
	                                	favi_icon_url='http://www.google.com/favicon.ico';
	                                }
                                }else{
                                	favi_icon_url='http://www.google.com/favicon.ico';
                                }
                                
                                //favi_icon_url='http://www.google.com/favicon.ico';
                                labelContent = labelContent +  "<a class='plain' href='" + urlNodeValue + "' target='_blank' title='" + titleNodeValue + "'><img src=\""+favi_icon_url+"\" height=\"16px\" width=\"16px\"> " + titleNodeValue.substring(0,100) + "<br/><span class='bookmarkURL'>"+urlNodeValue.substring(0,70)+"...</span></a>";
                            }

                            
                            
                            document.getElementById('label'+labelNumber).innerHTML = document.getElementById('label'+labelNumber).innerHTML + labelContent;


                        } else {
                            document.write("No ResponseXML");
                        }
                    }
                }

                // open up the document using HTTP GET
                labelNameStr = escape(labelName);
                labelNameStr = labelNameStr.replace(/%20/g,"+");
                var bookmarksForLabel = "http://www.google.com/bookmarks/?output=xml&num=100000&lookup&q=label:\"" + labelNameStr + "\"";
                document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + "<br/> LABEL XML -  "+bookmarksForLabel;
                xhr1.open("GET", bookmarksForLabel, true);
                xhr1.send(null);

            } catch(e) {
                document.write("Please Login to Google Bookmarks!");
            }
        }

        /**
         * generate a unique array sorted
         * @param arrayName
         */
        function unique(arrayName) {
            var newArray = new Array();

            label:for (var i = 0; i < arrayName.length; i++) {
                for (var j = 0; j < newArray.length; j++) {
                    if (newArray[j] == arrayName[i])
                        continue label;
                }
                newArray[newArray.length] = arrayName[i];
            }
            return newArray;
        }


        /**
         *  get all the bookmarks from google (must be logged in to get data)
         */
        function displayBookmarks() {

            // create a new request object
            var xhr = new XMLHttpRequest();

            if (xhr.length <= 0) {
                document.write("Please login!");
            }


            try {
                // if we have an onReadyStateChange of 4 then we can read the XML
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4) {
                        if (xhr.responseXML) {

                            xmlDoc = xhr.responseXML;
                            
                            getTotalNumGoogleBookmarks();
                            getLabels();
                            getGoogleManagmentLinks();
							//getBookmarks();
							
							setIcon('book.png');
							

                        } else {
                            document.write("<div>");
                        	document.write("<a href=\"#\" onClick=\"goToBookmark(googlebookmarks)\"><img src=\"book_key.png\" align=\"top\"> Please click here to login</a>");
                        	document.write("</div>");
							
							setIcon('book_error.png');
							chrome.browserAction.setBadgeText({text:""});
                        }
                    }
                }
				
				if (xhr.length == 0) {
                	document.write("<div>");
                	document.write("<a href=\"#\" onClick=\"goToBookmark(googlebookmarks)\"><img src=\"book_key.png\"  align=\"top\"> Please click here to login</a>");
                	document.write("</div>");
					
					setIcon('book_error.png');
					chrome.browserAction.setBadgeText({text:""});
                }

                // open up the document using HTTP GET
                xhr.open("GET", bookmarksXML, true);
                xhr.send(null);
            } catch(e) {
                document.write("<div>");
				document.write("<a href=\"#\" onClick=\"goToBookmark(googlebookmarks)\"><img src=\"book_key.png\" align=\"top\"> Please click here to login</a>");
				document.write("</div>");   
				
				setIcon('book_error.png');
				chrome.browserAction.setBadgeText({text:""});				}
        }

        /**
         * Go to the bookmarks and download them as XML
         * @param passedUrl
         */
        function goToBookmark(passedUrl) {
            alert("opening new tab for url: " + passedUrl);
            chrome.tabs.create({url: passedUrl});
        }

		function setIcon(imgPath) {
            var path = imgPath;
            try {
                var img = new Image();
                img.onerror = function() {
                    console.error("Could not set icon: " + path);
                    iconSet = localStorage["gr_icon_set"] = "set1";
                    setIcon(imgPath);
                }
                img.onload = function() {
                    var canvas = document.createElement("canvas");
                    canvas.width = img.width > 19 ? 19 : img.width;
                    canvas.height = img.height > 19 ? 19 : img.height;

                    var canvas_context = canvas.getContext('2d');
                    canvas_context.clearRect(0, 0, canvas.width, canvas.height);
                    canvas_context.drawImage(img, 0, 0, canvas.width, canvas.height);
                    var imgData = canvas_context.getImageData(0, 0, canvas.width, canvas.height);
                    chrome.browserAction.setIcon({imageData: imgData});
                    delete imgData;
                }
                img.src = path;
            } catch(e) { 

            }
        } 
		
		function toggleLayer( whichLayer ){
			document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + "<br/> WhichLayer = "+whichLayer; 
			var elem, vis;
		  elem = document.getElementById( whichLayer );
		  vis = elem.style;
		  // if the style.display value is blank we try to figure it out here
		  
		  document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + "<br/> WhichLayer vis.display= "+vis.display;

		  document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + "<br/> WhichLayer innerHTML= "+elem.innerHTML;
		  
		  if (vis.display == '' || vis.display == 'block'){
			  vis.display ='none';
		  }else{
			  vis.display ='block';
		  }
		  
		  
		}

    </script>

</head>
<body onload="displayBookmarks();">
<div id="debugMessages"></div>
<a href="#" onClick="toggleLayer('bookmarkListcontainer');return false;">toggle</a>
<div id="bookmarkListcontainer" style="width:400px;">
	<center style="font-size:12px;padding:6px;">
			<img src="loading.gif" align="top"> Loading please wait...
	</center>
</div>

<script>
document.getElementById('debugMessages').innerHTML =  document.getElementById('debugMessages').innerHTML + "<br/> TEST DEBUG  ";
</script>
</body>
</html>